<template>
  <div class="role-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="角色名称">
          <el-input v-model="queryParams.name" placeholder="请输入角色名称" clearable/>
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="queryParams.code" placeholder="请输入角色编码" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="table-card">
      <template #header>
        <el-button type="primary" @click="handleAdd">新增角色</el-button>
      </template>

      <!-- 表格 -->
      <el-table :data="roleList" border v-loading="loading">
        <el-table-column type="index" label="序号" width="50"/>
        <el-table-column prop="name" label="角色名称"/>
        <el-table-column prop="code" label="角色编码"/>
        <el-table-column prop="description" label="描述"/>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="handlePermission(scope.row)">权限</el-button>
            <el-button type="primary" link @click="handleUsers(scope.row)">用户</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="roleFormRef" :model="roleForm" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色编码" :disabled="dialogType === 'edit'"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" placeholder="请输入描述"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog
      title="权限配置"
      v-model="permissionDialogVisible"
      width="400px"
      append-to-body
    >
      <el-tree
        ref="menuTree"
        :data="menuList"
        :props="{ label: 'name' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="selectedMenuIds"
        :default-expand-all="true"
      />
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPermission">确定</el-button>
      </template>
    </el-dialog>

    <!-- 关联用户对话框 -->
    <el-dialog
      title="关联用户"
      v-model="userDialogVisible"
      width="800px"
      append-to-body
    >
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="userQueryParams">
        <el-form-item label="用户名">
          <el-input v-model="userQueryParams.username" placeholder="请输入用户名" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUserQuery">查询</el-button>
          <el-button @click="handleAddUser">添加用户</el-button>
        </el-form-item>
      </el-form>

      <!-- 已关联用户表格 -->
      <el-table :data="userList" border v-loading="userLoading">
        <el-table-column type="index" label="序号" width="50"/>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="nickname" label="昵称"/>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="danger" link @click="handleRemoveUser(scope.row)">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="userQueryParams.current"
          v-model:page-size="userQueryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="userTotal"
          layout="total, sizes, prev, pager, next"
          @size-change="handleUserSizeChange"
          @current-change="handleUserCurrentChange"
        />
      </div>
    </el-dialog>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      v-model="addUserDialogVisible"
      width="800px"
      append-to-body
    >
      <!-- 用户搜索 -->
      <el-form :inline="true" :model="addUserQueryParams">
        <el-form-item label="用户名">
          <el-input v-model="addUserQueryParams.username" placeholder="请输入用户名" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchUsers">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 可选用户表格 -->
      <el-table 
        :data="availableUsers" 
        border 
        v-loading="addUserLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="nickname" label="昵称"/>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="addUserQueryParams.current"
          v-model:page-size="addUserQueryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="availableUserTotal"
          layout="total, sizes, prev, pager, next"
          @size-change="handleAddUserSizeChange"
          @current-change="handleAddUserCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="addUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddUsers">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/utils/request'

// 表单ref
const roleFormRef = ref(null)

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  name: '',
  code: ''
})

// 角色列表数据
const roleList = ref([])
const total = ref(0)
const loading = ref(false)

// 获取角色列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request('/api/role/list', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(queryParams)
    })
    if (res.code === 200) {
      roleList.value = res.data.records
      total.value = Number(res.data.total)
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询和重置
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

const resetQuery = () => {
  queryParams.name = ''
  queryParams.code = ''
  handleQuery()
}

// 分页
const handleSizeChange = (val) => {
  queryParams.size = val
  queryParams.current = 1
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.current = val
  getList()
}

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const dialogTitle = ref('新增角色')
const roleForm = reactive({
  id: undefined,
  name: '',
  code: '',
  description: '',
  status: 1
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]{2,20}$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 重置表单
const resetForm = () => {
  roleForm.id = undefined
  roleForm.name = ''
  roleForm.code = ''
  roleForm.description = ''
  roleForm.status = 1
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
}

// 新增角色
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '新增角色'
  resetForm()
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑角色'
  resetForm()
  try {
    const res = await request(`/api/role/get?id=${row.id}`)
    if (res.code === 200) {
      Object.assign(roleForm, res.data)
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取角色详情失败:', error)
  }
}

// 提交表单
const submitForm = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    
    const url = dialogType.value === 'add' ? '/api/role/add' : '/api/role/update'
    
    const res = await request(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(roleForm)
    })
    
    if (res.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功')
      dialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该角色吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request(`/api/role/delete?id=${row.id}`, {
        method: 'GET'
      })
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      }
    } catch (error) {
      console.error('删除角色失败:', error)
    }
  })
}

// 权限配置相关
const permissionDialogVisible = ref(false)
const menuList = ref([])
const selectedMenuIds = ref([])
const currentRoleId = ref()
const menuTree = ref(null)

// 打开权限配置
const handlePermission = async (row) => {
  currentRoleId.value = row.id
  try {
    // 获取菜单树
    const menuRes = await request('/api/menu/tree')
    if (menuRes.code === 200) {
      menuList.value = menuRes.data
    }
    // 获取角色已有权限
    const roleRes = await request(`/api/role/get?id=${row.id}`)
    if (roleRes.code === 200) {
      selectedMenuIds.value = roleRes.data.menuIds || []
    }
    permissionDialogVisible.value = true
  } catch (error) {
    console.error('获取权限数据失败:', error)
    ElMessage.error('获取权限数据失败')
  }
}

// 提交权限配置
const submitPermission = async () => {
  try {
    // 获取选中的菜单ID数组
    const checkedKeys = menuTree.value.getCheckedKeys()
    const halfCheckedKeys = menuTree.value.getHalfCheckedKeys()
    const menuIds = [...checkedKeys, ...halfCheckedKeys]
    
    const res = await request(`/api/role/${currentRoleId.value}/menus`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(menuIds)
    })
    
    if (res.code === 200) {
      ElMessage.success('权限配置成功')
      permissionDialogVisible.value = false
    }
  } catch (error) {
    console.error('提交权限配置失败:', error)
    ElMessage.error('提交权限配置失败')
  }
}

// 关联用户相关
const userDialogVisible = ref(false)
const userList = ref([])
const userTotal = ref(0)
const userLoading = ref(false)
const userQueryParams = reactive({
  current: 1,
  size: 10,
  username: '',
  roleId: undefined
})

// 查看关联用户
const handleUsers = async (row) => {
  currentRoleId.value = row.id
  userQueryParams.roleId = row.id
  userQueryParams.current = 1
  await getRoleUsers()
  userDialogVisible.value = true
}

// 用户查询
const handleUserQuery = () => {
  userQueryParams.current = 1
  getRoleUsers()
}

// 重置用户查询
const resetUserQuery = () => {
  userQueryParams.username = ''
  handleUserQuery()
}

// 获取角色关联的用户列表
const getRoleUsers = async () => {
  userLoading.value = true
  try {
    const res = await request(`/api/role/${currentRoleId.value}/users`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(userQueryParams)
    })
    if (res.code === 200) {
      userList.value = res.data.records
      userTotal.value = Number(res.data.total)
    }
  } catch (error) {
    console.error('获取角色用户列表失败:', error)
    ElMessage.error('获取角色用户列表失败')
  } finally {
    userLoading.value = false
  }
}

// 用户列表分页
const handleUserSizeChange = (val) => {
  userQueryParams.size = val
  getRoleUsers()
}

const handleUserCurrentChange = (val) => {
  userQueryParams.current = val
  getRoleUsers()
}

// 添加用户相关数据
const addUserDialogVisible = ref(false)
const addUserLoading = ref(false)
const availableUsers = ref([])
const availableUserTotal = ref(0)
const selectedUsers = ref([])
const addUserQueryParams = reactive({
  current: 1,
  size: 10,
  username: ''
})

// 打开添加用户对话框
const handleAddUser = () => {
  addUserDialogVisible.value = true
  searchUsers()
}

// 查询可选用户
const searchUsers = async () => {
  addUserLoading.value = true
  try {
    const res = await request(`/api/role/${currentRoleId.value}/available-users`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(addUserQueryParams)
    })
    if (res.code === 200) {
      availableUsers.value = res.data.records
      availableUserTotal.value = Number(res.data.total)
    }
  } catch (error) {
    console.error('获取可选用户列表失败:', error)
    ElMessage.error('获取可选用户列表失败')
  } finally {
    addUserLoading.value = false
  }
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 提交添加用户
const submitAddUsers = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要添加的用户')
    return
  }

  try {
    const userIds = selectedUsers.value.map(user => user.id)
    const res = await request(`/api/role/${currentRoleId.value}/users/add`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userIds)
    })

    if (res.code === 200) {
      ElMessage.success('添加用户成功')
      addUserDialogVisible.value = false
      getRoleUsers() // 刷新已关联用户列表
    }
  } catch (error) {
    console.error('添加用户失败:', error)
  }
}

// 移除用户
const handleRemoveUser = async (user) => {
  try {
    await ElMessageBox.confirm('确认要移除该用户吗?', '提示', {
      type: 'warning'
    })
    
    const res = await request(`/api/role/${currentRoleId.value}/users/${user.id}`, {
      method: 'DELETE'
    })

    if (res.code === 200) {
      ElMessage.success('移除用户成功')
      getRoleUsers() // 刷新用户列表
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除用户失败:', error)
    }
  }
}

// 添加用户分页处理
const handleAddUserSizeChange = (val) => {
  addUserQueryParams.size = val
  searchUsers()
}

const handleAddUserCurrentChange = (val) => {
  addUserQueryParams.current = val
  searchUsers()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.role-container {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
